<template>
  <div class="app-container">
    <el-form ref="dataForm" :model="dataForm" status-icon label-width="300px">
      <el-form-item v-for="(item, index) in dataForm.payType" :label="$t('支付方式')">
        <el-col :span="4">
          <el-input v-model="item[0]" @change="changePayType(index, item[0])"></el-input>
        </el-col>
        <el-col :span="4">
            <el-button type="danger" size="small" @click="deletePayType(index)" icon="el-icon-delete" style="margin-left:10px">{{$t('Delete')}}</el-button>
        </el-col>
      </el-form-item>
    </el-form>
    <!-- <div align="center">{{$t('说明：此配置为配置统计金额的横坐标金额范围')}}</div> -->
    <div class="dialog-footer" style="margin-left:300px;">
      <!-- <el-tooltip class="item" effect="light" :content="$t('Add')" placement="top-start"> -->
        <el-button type="primary" @click="addPayType" icon="el-icon-plus">{{$t('Add')}}</el-button>
      <!-- </el-tooltip> -->
      <el-button type="primary" @click="handleUpdate" icon="el-icon-check">{{ $t('Confirm') }}</el-button>
    </div>
  </div>
</template>

<script>
import { listPayType, updatePayType } from '@/api/config'

export default {
  name: 'configPayType',
  data() {
    return {
      dataForm: {
        payType: []
      },
      value: [1, 100],
    }
  },
  created() {
    this.init()
  },
  methods: {
    init: function () {
      listPayType().then(response => {
        let tmp = response.data.data.litemall_pay_type
        if (tmp) {
          let arr = tmp.split(';')
          arr.forEach(data => {
            let t = data.split('-')
            this.dataForm.payType.push(t)
          })
        }
      })
    },
    addPayType() {
      let length = this.dataForm.payType.length;
      this.dataForm.payType.push(["", length + 1])
    },
    deletePayType(index) {
      this.dataForm.payType.splice(index, 1)
    },
    handleUpdate() {
      let body = ''
      this.dataForm.payType.forEach((arr, index) => {
        if (index != this.dataForm.payType.length - 1) {
          body += arr.join('-') + ';'
        } else {
          body += arr.join('-')
        }
      })

      updatePayType({ litemall_pay_type: body }).then(response => {
        this.$notify.success({
          title: this.$t('Success!'),
          message: this.$t('修改成功')
        })
      }).catch(response => {
        this.$notify.error({
          title: this.$t('Failed'),
          message: this.$t(response.data.errmsg)
        })
      })
    },
    changePayType(index, value) {
      let num = 0;
      for (let lengthKey in this.dataForm.payType) {
        if (value == this.dataForm.payType[lengthKey][0]) {
          num++
        }

      }
      if (num > 1) {
        this.$notify.error({
          title: this.$t('Failed'),
          message: this.$t("该支付方式已存在")
        })
        return false;
      } {
        return true;
      }
    },
  }
}
</script>

<style scoped>
.demonstration {
  font-size: 14px;
  color: #8492a6;
  line-height: 44px;
}
</style>
